// cart
const express = require("express");
const router = express.Router();
const {
  createCart,
  addToCart,
  getCart,
  deleteFromCart,
  updateCart
} = require("../utils/sql");


// 添加商品到购物车
router.post("/cart", async (req, res) => {
  const { user: { user_id, username, phone_number }, dish } = req.body;
  try {
    await createCart(user_id, username, phone_number);
    for (let i = 0; i < dish.length; i++) {
      await addToCart(user_id, dish[i].dish_id, dish[i].dish_name, dish[i].price, dish[i].image_url, dish[i].count);
    }
    res.send({ code: 200, message: "添加成功" });
  } catch (err) {
    console.error(err);
    res.send({ code: 0, message: "添加失败" });
  }
});


// 获取购物车和购物车项，根据用户id
router.post("/getCart", async (req, res) => {
  const { user_id } = req.body;
  try {
    const result = await getCart(user_id);
    res.send({ code: 200, message: "获取成功", data: result });
  } catch (err) {
    console.error(err);
    res.send({ code: 0, message: "获取失败" });
  }
});

// 修改购物车项数量
router.post("/updateCart", async (req, res) => {
  console.log(req.body);
  const { id, count } = req.body;
  try {
    await updateCart(id, count);
    res.send({ code: 200, message: "修改成功" });
  } catch (err) {
    console.error(err);
    res.send({ code: 0, message: "修改失败" });
  }
});

// 从购物车中删除商品
router.post("/deleteFromCart", async (req, res) => {
  console.log(req.body);
  const { id } = req.body;
  try {
    await deleteFromCart(id);
    res.send({ code: 200, message: "删除成功" });
  } catch (err) {
    console.error(err);
    res.send({ code: 0, message: "删除失败" });
  }
});



module.exports = router;
